/**
 * window.sessionStorage 浏览器临时缓存
 * @method set 设置临时缓存
 * @method get 获取临时缓存
 * @method remove 移除临时缓存
 * @method clear 移除全部临时缓存
 */
export const Session = {
	// 设置临时缓存
	set(key, val, needEncode = false, expired=10) {//默认过期时间
		if (needEncode) {
			val = encodeURIComponent(JSON.stringify(val))
      window.sessionStorage.setItem(key, val);
		} else {
      window.sessionStorage.setItem(key, JSON.stringify(val));
    }
		if (expired) {
            window.sessionStorage.setItem(`${key}__expires__`, `${Date.now() + 1000 * 60 * expired}`);
        }
	},
	// 获取临时缓存
	get(key, needDecode = false) {

		const expired = window.sessionStorage.getItem(`${key}__expires__`) || Date.now();
    const now = Date.now() + 1;
    if (now >= Number(expired)) {
        window.sessionStorage.removeItem(key);
        window.sessionStorage.removeItem(`${key}__expires__`);
        return;
    }

		let json = window.sessionStorage.getItem(key);
		if (needDecode) {
			json = decodeURIComponent(json)
		}
		return JSON.parse(json);
	},
	// 移除临时缓存
	remove(key) {
		window.sessionStorage.removeItem(key);
	},
	// 移除全部临时缓存
	clear() {
		window.sessionStorage.clear();
	},
};
